package com.bdult.vh.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.bdult.vh.common.CommonUtil;
import com.bdult.vh.service.ItemService;
import com.bdult.vh.service.MemberService;
import com.bdult.vh.service.OrderService;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	@Autowired
	private ItemService itemService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private MemberService memberService;
	
	@RequestMapping(value="main")
	public ModelAndView home(Model model, HttpServletRequest request, HttpSession session) {		
		ModelAndView mv = new ModelAndView();
		String goPage = "home";
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("BANNERCL", "V");	//이게 뭔가? "P", "R", "S", "U", "V" 이렇게 있는데 상품정보에서는 V를 쓰고 있다
		map.put("CATEGORY", "0101");
		map.put("ROWNUM", 10);
		
		ArrayList<HashMap<String,String>> itemList = new ArrayList<HashMap<String,String>>();
		itemList = itemService.getItemList(map);
		
		for(HashMap<String,String> item : itemList) {
			//이미지 가져오기
			String prdimg1 = item.get("PRDIMG1");
			prdimg1 = CommonUtil.encodeURL(prdimg1, "utf-8");
			item.put("PRDIMG1_ENC", prdimg1);
			
			//옵션 가져오기
			String sapcd = "";
			String lmtordcnt = "";
			ArrayList<HashMap<String,String>> optList = itemService.getItemOption(item.get("PRDCD"));
			System.out.println("opt = " + optList);
			
			if(optList != null ) {
				if(optList.size() > 0 ) {
					HashMap<String,String> opt = optList.get(0);
					sapcd = opt.get("SAPCD");
					lmtordcnt = String.valueOf( opt.get("LMTORDCNT") );
					
				}
			}
			item.put("SAPCD", sapcd);
			item.put("LMTORDCNT", lmtordcnt);
		}		
		mv.addObject("itemList", itemList);
		
		//쿠폰정보
		int iCouponTotal = 0;
		if(request.getSession().getAttribute("cstmno") != null) {
			String cstmno = String.valueOf(request.getSession().getAttribute("cstmno"));
			
			HashMap<String, Object> pMap = new HashMap<String, Object>();
			pMap.put("cstmno", Long.valueOf(cstmno).longValue());
			pMap.put("prdcd", "");
			
			HashMap<String, Object> couponTT = new HashMap<String, Object>();
			couponTT = orderService.getCouponTotal(cstmno);
			iCouponTotal = Integer.parseInt( couponTT.get("COUPONCNT").toString() );
		}
		
		mv.addObject("couponTotal", iCouponTotal);
		
		//자동 로그인 체크
		String member_id = "";
		String member_pwd = "";
		String auto_login = "";
		
		String name   = "";
		String value   = "";
		Cookie[] cookies = request.getCookies();
	    if(cookies != null){
			System.out.println("cookie 수 = " + cookies.length);
	        for (int i = 0; i < cookies.length; i++) {
				  name  = cookies[i].getName();
				  value  = cookies[i].getValue();
				  System.out.println(i + ".COOKIES NAME : " + name + " / VALUE : " + value);
				  
				  if(name.equals("member_id")) {
					  member_id = value;
				  }
				  if(name.equals("auto_login")) {
					  auto_login = value;
				  }
				  if(name.equals("member_pwd")) {
					  member_pwd = value;
				  }
			 }
		}
	    
	    //자동 로그인 처리 
	    if(!member_id.equals("") && !member_pwd.equals("") && !auto_login.equals("Y") ) {
	    	System.out.println("auto login start");
	    	System.out.println("member_id=" + member_id + " member_pwd=" + member_pwd + " auto_login=" + auto_login);
			
			HashMap member_map = new HashMap<String,String>();
			member_map.put("id", member_id);
			member_map.put("pwd", member_pwd);
			
			HashMap result_map = new HashMap<String,String>();
			result_map = memberService.loginCheck(member_map);
			if(result_map!=null){
				session.setAttribute("member_id", result_map.get("CSTMID"));
				session.setAttribute("member_name", result_map.get("CSTMNM"));
				session.setAttribute("cstmno", result_map.get("CSTMNO"));
			} else {
				goPage = "redirect:/member/login.vh";

			    mv.addObject("rsltmsg","로그인 정보를 다시 확인하여주십시요.");
			}
	    }

	    mv.setViewName(goPage);
		mv.addObject("LOC", "MAIN");
		return mv;
	}
	
	@RequestMapping(value="best")
	public ModelAndView best(Model model, HttpServletRequest request) {		
		ModelAndView mv = new ModelAndView();
		
		ArrayList<HashMap<String,String>> itemList = new ArrayList<HashMap<String,String>>();
		itemList = itemService.getItemList_best();
		
		for(HashMap<String,String> item : itemList) {
			//이미지 가져오기
			String prdimg1 = item.get("PRDIMG1");
			prdimg1 = CommonUtil.encodeURL(prdimg1, "utf-8");
			item.put("PRDIMG1_ENC", prdimg1);
			
			//옵션 가져오기
			String sapcd = "";
			String lmtordcnt = "";
			ArrayList<HashMap<String,String>> optList = itemService.getItemOption(item.get("PRDCD"));
			System.out.println("opt = " + optList);
			
			if(optList != null ) {
				if(optList.size() > 0 ) {
					HashMap<String,String> opt = optList.get(0);
					sapcd = opt.get("SAPCD");
					lmtordcnt = String.valueOf( opt.get("LMTORDCNT") );
					
				}
			}
			item.put("SAPCD", sapcd);
			item.put("LMTORDCNT", lmtordcnt);
		}
		
		mv.addObject("itemList", itemList);
		
		mv.setViewName("best");
		mv.addObject("LOC", "BEST");
		return mv;
	}
	
	@RequestMapping(value="category")
	public ModelAndView category(Model model, @RequestParam Map<String, Object> paramMap) {		
		ModelAndView mv = new ModelAndView();
		String s_catcd = paramMap.get("s_catcd").toString();
		ArrayList<HashMap<String,String>> itemList = new ArrayList<HashMap<String,String>>();
		
		//paging
		int current_page = 0;
		int max_elem = 10;
		System.out.println("****** " + paramMap);
		if(paramMap.get("current_page")!=null) {
			current_page = Integer.parseInt( (String) paramMap.get("current_page") );
		}
		if(paramMap.get("max_elem")!=null) {
			max_elem = Integer.parseInt( (String) paramMap.get("max_elem") );
		}
		mv.addObject("current_page", current_page);
		mv.addObject("max_elem", max_elem);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("CATEGORY", s_catcd);
		map.put("START_NUM", current_page * 10);
		map.put("END_NUM", max_elem);
		
		itemList = itemService.getItemList_category(map);
		System.out.println(itemList);
		String tot_cnt = "0";
		
		for(HashMap<String,String> item : itemList) {
			//이미지 가져오기
			String prdimg1 = item.get("PRDIMG1");
			prdimg1 = CommonUtil.encodeURL(prdimg1, "utf-8");
			item.put("PRDIMG1_ENC", prdimg1);
			
			//옵션 가져오기
			String sapcd = "";
			String lmtordcnt = "";
			ArrayList<HashMap<String,String>> optList = itemService.getItemOption(item.get("PRDCD"));
			System.out.println("opt = " + optList);
			
			if(optList != null ) {
				if(optList.size() > 0 ) {
					HashMap<String,String> opt = optList.get(0);
					sapcd = opt.get("SAPCD");
					lmtordcnt = String.valueOf( opt.get("LMTORDCNT") );
					
				}
			}
			item.put("SAPCD", sapcd);
			item.put("LMTORDCNT", lmtordcnt);
			
			//총 갯수 구하기
			tot_cnt = String.valueOf( item.get("TOT_CNT") );
		}
		mv.addObject("tot_cnt", tot_cnt);
		
		mv.addObject("s_catcd", s_catcd);
		mv.addObject("itemList", itemList);
		mv.setViewName("category");
		return mv;
	}
	
	@RequestMapping(value="search")
	public ModelAndView search(Model model, @RequestParam Map<String, Object> paramMap) {		
		ModelAndView mv = new ModelAndView();
		ArrayList<HashMap<String,String>> itemList = new ArrayList<HashMap<String,String>>();
		System.out.println(paramMap);
		itemList = itemService.getItemList_keyword(paramMap);
		System.out.println(itemList);
		
		for(HashMap<String,String> item : itemList) {
			//이미지 가져오기
			String prdimg1 = item.get("PRDIMG1");
			prdimg1 = CommonUtil.encodeURL(prdimg1, "utf-8");
			item.put("PRDIMG1_ENC", prdimg1);
			
			//옵션 가져오기
			String sapcd = "";
			String lmtordcnt = "";
			ArrayList<HashMap<String,String>> optList = itemService.getItemOption(item.get("PRDCD"));
			System.out.println("opt = " + optList);
			
			if(optList != null ) {
				if(optList.size() > 0 ) {
					HashMap<String,String> opt = optList.get(0);
					sapcd = opt.get("SAPCD");
					lmtordcnt = String.valueOf( opt.get("LMTORDCNT") );
					
				}
			}
			item.put("SAPCD", sapcd);
			item.put("LMTORDCNT", lmtordcnt);
		}
		
		mv.addObject("itemList", itemList);
		mv.setViewName("home");
		return mv;
	}
	
	@RequestMapping(value="item_detail")
	public ModelAndView item_detail(Model model, @RequestParam Map<String, Object> paramMap, HttpServletRequest request) {
		
		ModelAndView mv = new ModelAndView();
		
		String prdcd = paramMap.get("prdcd").toString();
		Map<String,String> item = itemService.getItemData(prdcd);		
		String prdimg1 = item.get("PRDIMG1");
		prdimg1 = CommonUtil.encodeURL(prdimg1, "utf-8");
		item.put("PRDIMG1_ENC", prdimg1);
		mv.addObject("item", item);
		mv.addObject("itemoption", itemService.getItemOption(prdcd));

		mv.setViewName("item_detail");
		return mv;
	}
}
